<!DOCTYPE html>
<html>
<head>
    <title>WebSocket-Chat-stomp</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.6.1/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script>
        // 定义变量：stomp客户端
        var stompClient = null;
        var addUserName = "虚拟用户";
        // 接收消息
        function connect() {
            var socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                console.log('Connected: ' + frame);
                // 客户端订阅服务端消息（广播）
                stompClient.subscribe('/topic/public', function (message) {
                    showMessage(JSON.parse(message.body));
                });
            });
        }


        // 用户加入
        function addUser() {
            // 获取输入框元素
            var usernameInput = document.getElementById("username");
            var joinButton = document.getElementById("joinButton");
            // 禁用输入框
            usernameInput.disabled = true;
            // 禁用按钮
            joinButton.disabled = true;
            // 可选：弹出提示信息
            // alert("用户已加入，输入框已禁用！");
            var userName = usernameInput.value;
            // 用户名赋值
            addUserName =userName;
            // 处理消息
            if (userName && stompClient) {
                var chatMessage = {
                    sender: userName,
                    content: userName + "~~已加入聊天!请注意财产安全",
                    type: 'JOIN'
                };
                stompClient.send("/app/chat.addUser", {}, JSON.stringify(chatMessage));
            }
        }


        // 发送消息
        function sendMessage() {
            var messageContent = document.getElementById("message").value;
            // 往服务端发送消息
            stompClient.send("/app/chat.sendMessage", {}, JSON.stringify({
                sender: addUserName,
                content: messageContent,
                type: 'CHAT'
            }));
        }
        // 展示消息
        function showMessage(message) {
            var response = document.getElementById("response");
            var p = document.createElement("p");
            p.appendChild(document.createTextNode(message.sender + ": " + message.content));
            response.appendChild(p);
        }

        // 用户离开的消息提示
        function leaveChat() {
            if (stompClient) {
                var chatMessage = {
                    sender: addUserName,
                    content: addUserName + "~~已离开聊天",
                    type: 'LEAVE'
                };
                stompClient.send("/app/chat.leave", {}, JSON.stringify(chatMessage));
                // todo 延迟断开连接，确保服务器有时间处理消息
                setTimeout(function() {
                    stompClient.disconnect();
                    console.log("Disconnected");
                }, 500); // 500毫秒延迟
            }
        }
        // todo 监听窗口关闭事件
        window.onbeforeunload = function() {
            leaveChat();
        };
    </script>
</head>
<body onload="connect()">
<div>

    <input type="text" id="username" placeholder="输入您的姓名" />
    <button id="joinButton" onclick="addUser()">用户加入</button>
    <input type="text" id="message" />
    <button onclick="sendMessage()">发送信息</button>
    <br>
    <button onclick="leaveChat()">离开</button>
</div>
<div id="response"></div>
</body>
</html>
